<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="visible" title="筛选模板消息目标用户">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getWxUsers()" clearable ref="dataForm">
      <el-form-item>
        <el-select multiple @change="getWxUsers()" filterable placeholder="用户标签" v-model="dataForm.tagidList">
          <el-option :key="item.id" :label="item.name" :value="item.id+''" v-for="item in wxUserTags"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input @change="getWxUsers()" clearable placeholder="昵称" v-model="dataForm.nickname"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input @change="getWxUsers()" clearable placeholder="省份" v-model="dataForm.province"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input @change="getWxUsers()" clearable placeholder="城市" v-model="dataForm.city"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input @change="getWxUsers()" clearable placeholder="备注" v-model="dataForm.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input @change="getWxUsers()" clearable placeholder="扫码场景值" v-model="dataForm.qrSceneStr"></el-input>
      </el-form-item>
    </el-form>
    <div class="text-bold">本消息将发送给：</div>
    <div class="user-list" v-loading="wxUsersLoading">
      <div :key="item.openid" class="user-card" v-for="item in wxUserList">
        <el-avatar :src="item.headimgurl"></el-avatar>
        <div class="nickname">{{item.nickname}}</div>
      </div>
      <div class="text-bold">
        <span v-show="totalCount>10">...</span>
        等共<span class="text-success">{{totalCount}}</span>个用户
      </div>
    </div>
    <div class="margin-top text-bold">消息预览：</div>
    <div class="margin-top-xs">
      <el-input autosize disabled placeholder="模版" type="textarea" v-model="msgReview"></el-input>
    </div>
    <span class="dialog-footer" slot="footer">
            <el-button :disabled="totalCount<=0 || sending" @click="send"
                       type="success">{{sending?'发送中...':'发送'}}</el-button>
            <el-button @click="visible=false">关闭</el-button>
        </span>
  </el-dialog>
</template>
<script>
  import {mapState} from 'vuex'
  import { listUser, getWxTags } from "@/api/wx/user";
  import { sendMsgBatch } from "@/api/wx/msgTemplate";
  export default {
    name: 'template-msg-task',
    props: {
      wxUserTagName: {
        type: String,
        required: false
      }
    },
    data() {
      return {
        visible: false,
        wxUsersLoading: false,
        sending: false,
        msgTemplate: {},
        dataForm: {
          pageNum: 1,
          pageSize: 10,
          appid: undefined,
          phone: undefined,
          nickname: undefined,
          sex: undefined,
          city: undefined,
          province: undefined,
          headimgurl: undefined,
          subscribeTime: undefined,
          subscribe: undefined,
          unionid: undefined,
          tagidList: [],
          subscribeScene: undefined,
          qrSceneStr: undefined
        },
        wxUserList: [],
        totalCount: 0
      }
    },
    computed: mapState({
      wxUserTags: state => state.wxUserTags.tags,
      msgReview() {
        if (!this.msgTemplate.data) return ""
        let content = this.msgTemplate.content
        this.msgTemplate.data.forEach(item => {
          content = content.replace("{{" + item.name + ".DATA}}", item.value)
        })
        return content
      }
    }),
    mounted() {
      this.getWxUserTags().then((taglist) => {
        if (this.wxUserTagName) {
          let tagItem = taglist.find(tag => tag.name == this.wxUserTagName)
          console.log(tagItem)
          if (tagItem) {
            this.dataForm.tagid = tagItem.id + ''
          }
        }
        this.getWxUsers()
      });
    },
    methods: {
      init(msgTemplate) {
        if (!msgTemplate || !msgTemplate.templateId) {
          this.$message.error('消息模板无效')
          return
        }
        if (!msgTemplate.data || !(msgTemplate.data instanceof Array)) {
          this.$message.error('请现配置此模板填充数据')
          return
        }
        this.msgTemplate = msgTemplate
        this.visible = true;
      },
      getWxUserTags() {
        return new Promise((resolve, reject) => {
          getWxTags().then(response => {
            this.$store.commit('wxUserTags/updateTags', response.data)
            resolve(response.list)
          });
        })
      },
      getWxUsers() {
        this.wxUsersLoading = true
        listUser(this.dataForm).then(response => {
          this.wxUserList = response.rows;
          this.totalCount = response.total;
          this.wxUsersLoading = false;
        });
      },
      send() {
        if (this.sending) return
        this.sending = true
        sendMsgBatch({
          wxUserFilterParams: this.dataForm,
          templateId: this.msgTemplate.templateId,
          url: this.msgTemplate.url,
          miniprogram: this.msgTemplate.miniprogram,
          data: this.msgTemplate.data,
        }).then(response => {
          this.$message.success("消息将在后台发送")
          this.visible = false
        }).finally(() => {
          this.sending = false;
        });
      }
    }
  }
</script>
<style scoped>
  .user-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .user-card {
    overflow: hidden;
    max-width: 60px;
    margin: 5px;
    text-align: center;
  }

  .nickname {
    color: #999999;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
